/*
 * To change this template, choose Tools | Templates and open the template in
 * the editor.
 */
package com.renangomes.malgo.gui;

import com.renangomes.malgo.agoritmos.Algo;
import com.renangomes.malgo.agoritmos.AlgoritmoFIFO;
import com.renangomes.malgo.agoritmos.AlgoritmoMRU;
import com.renangomes.malgo.agoritmos.AlgoritmoNUR;
import com.renangomes.malgo.agoritmos.AlgoritmoSC;
import com.renangomes.malgo.entidades.Pagina;
import com.renangomes.malgo.gui.cellrenders.CellRenderCadeiaDeReferencias;
import java.util.ArrayList;
import javax.swing.AbstractListModel;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.ListModel;

/**
 *
 * @author RenanGomes
 */
public final class JanelaPrincipal extends JFrame {

    public Pagina[] memoria;
    public ArrayList<Pagina> disco = new ArrayList<Pagina>();
    public static JanelaPrincipal janela;
    public ArrayList<Integer> cadeia = new ArrayList<Integer>();
    public static int posicaoCadeia = 0;
    private AlgoritmoNUR anur;
    private AlgoritmoFIFO afifo;
    private AlgoritmoSC asc;
    private AlgoritmoMRU amru;

    /**
     * Creates new form JanelaPrincipal
     */
    public JanelaPrincipal() {
        initComponents();
        setIconImage(new ImageIcon(JanelaPrincipal.class.getResource("/com/renangomes/malgo/gui/imgs/Drives-RAM-Drive-icon64.png")).getImage());
        memoria = new Pagina[getEspacosMen()];
        setLocationRelativeTo(null);
        setExtendedState(JFrame.MAXIMIZED_BOTH);
        inicializaLista();
        carregaExemplo();
        atualizaCadeia();
        setVisible(true);
        inicializaAlgoritmos();

    }

    public int getEspacosMen() {
        if (mcb3.isSelected()) {
            return 3;
        }
        if (mcb4.isSelected()) {
            return 4;
        }
        if (mcb5.isSelected()) {
            return 5;
        }
        if (mcb6.isSelected()) {
            return 6;
        }
        return 7;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        espacosMen = new javax.swing.ButtonGroup();
        algoritmos = new javax.swing.ButtonGroup();
        split = new javax.swing.JSplitPane();
        mFisica = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        lMemoria = new javax.swing.JList();
        mDisco = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        lDisco = new javax.swing.JList();
        jPanel3 = new javax.swing.JPanel();
        bReiniciar = new javax.swing.JButton();
        btProcessar = new javax.swing.JButton();
        btProcessarTudo = new javax.swing.JButton();
        jPanel4 = new javax.swing.JPanel();
        jScrollPane3 = new javax.swing.JScrollPane();
        lCadeia = new javax.swing.JList();
        pAlgo = new javax.swing.JPanel();
        menu = new javax.swing.JMenuBar();
        mArquivo = new javax.swing.JMenu();
        jMenuItem3 = new javax.swing.JMenuItem();
        jMenuItem1 = new javax.swing.JMenuItem();
        jMenuItem2 = new javax.swing.JMenuItem();
        jSeparator1 = new javax.swing.JPopupMenu.Separator();
        mFechar = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();
        mALterar = new javax.swing.JMenuItem();
        mAlgoritmos = new javax.swing.JMenu();
        cbNUR = new javax.swing.JCheckBoxMenuItem();
        cbFIFO = new javax.swing.JCheckBoxMenuItem();
        cbSC = new javax.swing.JCheckBoxMenuItem();
        cbMRU = new javax.swing.JCheckBoxMenuItem();
        mConfiguracoes = new javax.swing.JMenu();
        jMenu1 = new javax.swing.JMenu();
        mcb3 = new javax.swing.JCheckBoxMenuItem();
        mcb4 = new javax.swing.JCheckBoxMenuItem();
        mcb5 = new javax.swing.JCheckBoxMenuItem();
        mcb6 = new javax.swing.JCheckBoxMenuItem();
        mcb7 = new javax.swing.JCheckBoxMenuItem();
        jSeparator2 = new javax.swing.JPopupMenu.Separator();
        cbSempreCAleatorias = new javax.swing.JCheckBoxMenuItem();
        mAjuda = new javax.swing.JMenu();
        mSobre = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Malgo - Uma ferramenta para o ensino dos algoritmos de substituição de página");

        split.setBackground(new java.awt.Color(255, 204, 0));
        split.setBorder(javax.swing.BorderFactory.createTitledBorder("Memória Virtual"));
        split.setDividerLocation(300);
        split.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);

        mFisica.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 153, 0), 5));

        lMemoria.setBackground(new java.awt.Color(204, 255, 204));
        lMemoria.setCellRenderer(new com.renangomes.malgo.gui.cellrenders.CellRenderPagina());
        lMemoria.setFixedCellHeight(49);
        lMemoria.setVisibleRowCount(7);
        jScrollPane2.setViewportView(lMemoria);

        javax.swing.GroupLayout mFisicaLayout = new javax.swing.GroupLayout(mFisica);
        mFisica.setLayout(mFisicaLayout);
        mFisicaLayout.setHorizontalGroup(
            mFisicaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 218, Short.MAX_VALUE)
        );
        mFisicaLayout.setVerticalGroup(
            mFisicaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 274, Short.MAX_VALUE)
        );

        split.setTopComponent(mFisica);

        mDisco.setBackground(new java.awt.Color(153, 0, 0));
        mDisco.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(153, 0, 0), 5));
        mDisco.setOpaque(false);

        lDisco.setBackground(new java.awt.Color(255, 204, 204));
        lDisco.setCellRenderer(new com.renangomes.malgo.gui.cellrenders.CellRenderPagina(false));
        jScrollPane1.setViewportView(lDisco);

        javax.swing.GroupLayout mDiscoLayout = new javax.swing.GroupLayout(mDisco);
        mDisco.setLayout(mDiscoLayout);
        mDiscoLayout.setHorizontalGroup(
            mDiscoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 218, Short.MAX_VALUE)
        );
        mDiscoLayout.setVerticalGroup(
            mDiscoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 153, Short.MAX_VALUE)
        );

        split.setRightComponent(mDisco);

        jPanel3.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        bReiniciar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/renangomes/malgo/gui/imgs/Button-Reload-icon32.png"))); // NOI18N
        bReiniciar.setText("Reiniciar");
        bReiniciar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bReiniciarActionPerformed(evt);
            }
        });

        btProcessar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/renangomes/malgo/gui/imgs/Button-Play-icon32.png"))); // NOI18N
        btProcessar.setText("Processar");
        btProcessar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btProcessarActionPerformed(evt);
            }
        });

        btProcessarTudo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/renangomes/malgo/gui/imgs/Button-Fast-Forward-icon32.png"))); // NOI18N
        btProcessarTudo.setText("Processar Tudo");
        btProcessarTudo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btProcessarTudoActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(bReiniciar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btProcessarTudo)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 159, Short.MAX_VALUE)
                .addComponent(btProcessar)
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(bReiniciar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btProcessar)
                    .addComponent(btProcessarTudo))
                .addContainerGap())
        );

        jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder("Cadeia de Referências"));

        jScrollPane3.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
        jScrollPane3.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);

        lCadeia.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        lCadeia.setCellRenderer(new CellRenderCadeiaDeReferencias());
        lCadeia.setFixedCellHeight(42);
        lCadeia.setLayoutOrientation(javax.swing.JList.HORIZONTAL_WRAP);
        lCadeia.setVisibleRowCount(1);
        jScrollPane3.setViewportView(lCadeia);

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 530, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pAlgo.setBorder(javax.swing.BorderFactory.createTitledBorder("Estado Interno da ULTIMA execução do Algoritmo"));
        pAlgo.setLayout(new java.awt.BorderLayout());

        mArquivo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/renangomes/malgo/gui/imgs/attachment16.png"))); // NOI18N
        mArquivo.setText("Arquivo");

        jMenuItem3.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.CTRL_MASK));
        jMenuItem3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/renangomes/malgo/gui/imgs/Files-New-File-icon16.png"))); // NOI18N
        jMenuItem3.setText("Novo");
        mArquivo.add(jMenuItem3);

        jMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.CTRL_MASK));
        jMenuItem1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/renangomes/malgo/gui/imgs/Open-icon16.png"))); // NOI18N
        jMenuItem1.setText("Abrir");
        mArquivo.add(jMenuItem1);

        jMenuItem2.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK));
        jMenuItem2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/renangomes/malgo/gui/imgs/document-save-icon16.png"))); // NOI18N
        jMenuItem2.setText("Salvar");
        mArquivo.add(jMenuItem2);
        mArquivo.add(jSeparator1);

        mFechar.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F4, java.awt.event.InputEvent.ALT_MASK));
        mFechar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/renangomes/malgo/gui/imgs/Delete-icon16.png"))); // NOI18N
        mFechar.setText("Fechar");
        mFechar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mFecharActionPerformed(evt);
            }
        });
        mArquivo.add(mFechar);

        menu.add(mArquivo);

        jMenu2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/renangomes/malgo/gui/imgs/Document-Flow-Chart-icon16.png"))); // NOI18N
        jMenu2.setText("Execução Atual");
        jMenu2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenu2ActionPerformed(evt);
            }
        });

        mALterar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/renangomes/malgo/gui/imgs/promotion16.png"))); // NOI18N
        mALterar.setText("Alterar Memória Aleatoriamente");
        mALterar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mALterarActionPerformed(evt);
            }
        });
        jMenu2.add(mALterar);

        menu.add(jMenu2);

        mAlgoritmos.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/renangomes/malgo/gui/imgs/import-export-icon16.png"))); // NOI18N
        mAlgoritmos.setText("Algoritmo");

        algoritmos.add(cbNUR);
        cbNUR.setSelected(true);
        cbNUR.setText("NUR - Não Usado Recentemente");
        cbNUR.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbNURActionPerformed(evt);
            }
        });
        mAlgoritmos.add(cbNUR);

        algoritmos.add(cbFIFO);
        cbFIFO.setText("FIFO - O primeiro a Entrar é o Primeiro a Sair");
        cbFIFO.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbFIFOActionPerformed(evt);
            }
        });
        mAlgoritmos.add(cbFIFO);

        algoritmos.add(cbSC);
        cbSC.setText("SC - Segunda Chance");
        cbSC.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbSCActionPerformed(evt);
            }
        });
        mAlgoritmos.add(cbSC);

        algoritmos.add(cbMRU);
        cbMRU.setText("MRU - Menos Recentemente Usada");
        cbMRU.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbMRUActionPerformed(evt);
            }
        });
        mAlgoritmos.add(cbMRU);

        menu.add(mAlgoritmos);

        mConfiguracoes.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/renangomes/malgo/gui/imgs/Categories-applications-system-icon16.png"))); // NOI18N
        mConfiguracoes.setText("Configurações");

        jMenu1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/renangomes/malgo/gui/imgs/Drives-RAM-Drive-icon16.png"))); // NOI18N
        jMenu1.setText("Espaço da Memória Física");

        mcb3.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_3, java.awt.event.InputEvent.CTRL_MASK));
        espacosMen.add(mcb3);
        mcb3.setText("3 molduras");
        mcb3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mcb3ActionPerformed(evt);
            }
        });
        jMenu1.add(mcb3);

        mcb4.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_4, java.awt.event.InputEvent.CTRL_MASK));
        espacosMen.add(mcb4);
        mcb4.setText("4 molduras");
        mcb4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mcb4ActionPerformed(evt);
            }
        });
        jMenu1.add(mcb4);

        mcb5.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_5, java.awt.event.InputEvent.CTRL_MASK));
        espacosMen.add(mcb5);
        mcb5.setSelected(true);
        mcb5.setText("5 molduras");
        mcb5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mcb5ActionPerformed(evt);
            }
        });
        jMenu1.add(mcb5);

        mcb6.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_6, java.awt.event.InputEvent.CTRL_MASK));
        espacosMen.add(mcb6);
        mcb6.setText("6 molduras");
        mcb6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mcb6ActionPerformed(evt);
            }
        });
        jMenu1.add(mcb6);

        mcb7.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_7, java.awt.event.InputEvent.CTRL_MASK));
        espacosMen.add(mcb7);
        mcb7.setText("7  molduras");
        mcb7.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mcb7ActionPerformed(evt);
            }
        });
        jMenu1.add(mcb7);

        mConfiguracoes.add(jMenu1);
        mConfiguracoes.add(jSeparator2);

        cbSempreCAleatorias.setSelected(true);
        cbSempreCAleatorias.setText("Sempre Criar Alterações Aleatoriamente");
        mConfiguracoes.add(cbSempreCAleatorias);

        menu.add(mConfiguracoes);

        mAjuda.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/renangomes/malgo/gui/imgs/Alarm-Help-and-Support-icon16.png"))); // NOI18N
        mAjuda.setText("Ajuda");

        mSobre.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/renangomes/malgo/gui/imgs/id_card16.png"))); // NOI18N
        mSobre.setText("Sobre");
        mSobre.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mSobreActionPerformed(evt);
            }
        });
        mAjuda.add(mSobre);

        menu.add(mAjuda);

        setJMenuBar(menu);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(split, javax.swing.GroupLayout.PREFERRED_SIZE, 240, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(pAlgo, javax.swing.GroupLayout.DEFAULT_SIZE, 562, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(split, javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(pAlgo, javax.swing.GroupLayout.DEFAULT_SIZE, 287, Short.MAX_VALUE)))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void mSobreActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mSobreActionPerformed
        abrirSobre();
    }//GEN-LAST:event_mSobreActionPerformed

    private void btProcessarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btProcessarActionPerformed
        processar();
    }//GEN-LAST:event_btProcessarActionPerformed

    private void bReiniciarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bReiniciarActionPerformed
        reiniciar();
    }//GEN-LAST:event_bReiniciarActionPerformed

    private void mFecharActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mFecharActionPerformed
        System.exit(0);
    }//GEN-LAST:event_mFecharActionPerformed

    private void mcb3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mcb3ActionPerformed
        reiniciar();
    }//GEN-LAST:event_mcb3ActionPerformed

    private void mcb4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mcb4ActionPerformed
        reiniciar();
    }//GEN-LAST:event_mcb4ActionPerformed

    private void mcb5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mcb5ActionPerformed
        reiniciar();
    }//GEN-LAST:event_mcb5ActionPerformed

    private void mcb6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mcb6ActionPerformed
        reiniciar();
    }//GEN-LAST:event_mcb6ActionPerformed

    private void mcb7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mcb7ActionPerformed
        reiniciar();
    }//GEN-LAST:event_mcb7ActionPerformed

    private void btProcessarTudoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btProcessarTudoActionPerformed

        while (posicaoCadeia < cadeia.size() - 1) {
            processar();
        }



    }//GEN-LAST:event_btProcessarTudoActionPerformed

    private void cbFIFOActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbFIFOActionPerformed
        inicializaAlgoritmos();
    }//GEN-LAST:event_cbFIFOActionPerformed

    private void cbNURActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbNURActionPerformed
        inicializaAlgoritmos();
    }//GEN-LAST:event_cbNURActionPerformed

    private void jMenu2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenu2ActionPerformed
    }//GEN-LAST:event_jMenu2ActionPerformed

    private void mALterarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mALterarActionPerformed
        criarAlteracoesAleatorias();
    }//GEN-LAST:event_mALterarActionPerformed

    private void cbSCActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbSCActionPerformed
        inicializaAlgoritmos();
    }//GEN-LAST:event_cbSCActionPerformed

private void cbMRUActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbMRUActionPerformed
    inicializaAlgoritmos();
}//GEN-LAST:event_cbMRUActionPerformed

    public void reiniciar() {
        memoria = new Pagina[getEspacosMen()];
        disco.clear();
        inicializaLista();
        posicaoCadeia = 0;
        inicializaAlgoritmos();
        atualizaCadeia();
        carregaDisco();
    }

    /** 
     * Abre a janela sobre
     **/
    private void abrirSobre() {
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                JanelaSobre j2 = new JanelaSobre();
                j2.setLocationRelativeTo(null);
                j2.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup algoritmos;
    private javax.swing.JButton bReiniciar;
    private javax.swing.JButton btProcessar;
    private javax.swing.JButton btProcessarTudo;
    private javax.swing.JCheckBoxMenuItem cbFIFO;
    private javax.swing.JCheckBoxMenuItem cbMRU;
    private javax.swing.JCheckBoxMenuItem cbNUR;
    private javax.swing.JCheckBoxMenuItem cbSC;
    private javax.swing.JCheckBoxMenuItem cbSempreCAleatorias;
    private javax.swing.ButtonGroup espacosMen;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JMenuItem jMenuItem3;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JPopupMenu.Separator jSeparator1;
    private javax.swing.JPopupMenu.Separator jSeparator2;
    private javax.swing.JList lCadeia;
    private javax.swing.JList lDisco;
    private javax.swing.JList lMemoria;
    private javax.swing.JMenuItem mALterar;
    private javax.swing.JMenu mAjuda;
    private javax.swing.JMenu mAlgoritmos;
    private javax.swing.JMenu mArquivo;
    private javax.swing.JMenu mConfiguracoes;
    private javax.swing.JPanel mDisco;
    private javax.swing.JMenuItem mFechar;
    private javax.swing.JPanel mFisica;
    private javax.swing.JMenuItem mSobre;
    private javax.swing.JCheckBoxMenuItem mcb3;
    private javax.swing.JCheckBoxMenuItem mcb4;
    private javax.swing.JCheckBoxMenuItem mcb5;
    private javax.swing.JCheckBoxMenuItem mcb6;
    private javax.swing.JCheckBoxMenuItem mcb7;
    private javax.swing.JMenuBar menu;
    private javax.swing.JPanel pAlgo;
    private javax.swing.JSplitPane split;
    // End of variables declaration//GEN-END:variables

    private void inicializaLista() {
        ListModel lm = new AbstractListModel() {

            @Override
            public int getSize() {
                return memoria.length;
            }

            @Override
            public Object getElementAt(int index) {
                return memoria[index];
            }
        };


        ListModel ld = new AbstractListModel() {

            @Override
            public int getSize() {
                return disco.size();
            }

            @Override
            public Object getElementAt(int index) {
                return disco.get(index);
            }
        };


        ListModel lcdr = new AbstractListModel() {

            @Override
            public int getSize() {
                return cadeia.size();
            }

            @Override
            public Object getElementAt(int index) {
                return cadeia.get(index);
            }
        };

        lMemoria.setModel(lm);
        lDisco.setModel(ld);
        lCadeia.setModel(lcdr);


    }

    private void carregaExemplo() {

        //Anomalia de Belady p/ memoria com 3 e 4 molduras
//        cadeia.add(0);
//        cadeia.add(1);
//        cadeia.add(2);
//        cadeia.add(3);
//        cadeia.add(0);
//        cadeia.add(1);
//        cadeia.add(4);
//        cadeia.add(0);
//        cadeia.add(1);
//        cadeia.add(2);
//        cadeia.add(3);
//        cadeia.add(4);
        //Anomalia de Belady
        
        
        cadeia.add(0);
        cadeia.add(2);
        cadeia.add(1);
        cadeia.add(3);
        cadeia.add(5);
        cadeia.add(4);
        cadeia.add(6);
        cadeia.add(3);
        cadeia.add(7);
        cadeia.add(4);
        cadeia.add(7);
        cadeia.add(3);
        cadeia.add(3);
        cadeia.add(5);
        cadeia.add(5);
        cadeia.add(3);
        cadeia.add(1);
        cadeia.add(1);
        cadeia.add(1);
        cadeia.add(7);
        cadeia.add(1);
        cadeia.add(3);
        cadeia.add(4);
        cadeia.add(1);

        for (int i = 0; i < 138; i++) {

            //Existe 20% de chance de repetir um dos ultimos 5 números
            if (Math.random() > 0.8f && cadeia.size() > 6) {
                cadeia.add(cadeia.get(cadeia.size() - (1 + (Math.round((float) Math.random() * 5)))));
            } else {
                cadeia.add((Math.round((float) Math.random() * 20)));
            }

        }

        carregaDisco();
    }

    private void carregaDisco() {
//        for (int i = 0; i < 20; i++) {
//            disco.add(new Pagina(i));
//        }
    }

    private void atualizaCadeia() {
        lCadeia.setSelectedIndex(posicaoCadeia);
        lCadeia.repaint();
    }

    public Algo getAlgo() {
        if (cbNUR.isSelected()) {
            return anur;
        } else {
            if (cbFIFO.isSelected()) {
                return afifo;
            } else {
                if (cbSC.isSelected()) {
                    return asc;
                } else {
                    return amru;
                }
            }
        }
    }

    private void processar() {

        Algo ag = this.getAlgo();




        ag.processar(memoria, disco, cadeia, posicaoCadeia);




        if (posicaoCadeia < cadeia.size() - 1) {
            posicaoCadeia++;
        }

        for (Pagina p : disco) {
            if (p != null) {
                p.setModificada(false);
                p.setReferenciada(false);

            }
        }
        for (Pagina p : memoria) {
            if (p != null) {
                p.setModificada(false);
                p.setReferenciada(false);
            }
        }


        if (cbSempreCAleatorias.isSelected()) {
            criarAlteracoesAleatorias();
        }



        atualizaCadeia();
        inicializaLista();
        pAlgo.removeAll();
        pAlgo.add(ag.getPanel());
        validate();
    }

    private void inicializaAlgoritmos() {
        anur = new AlgoritmoNUR();
        afifo = new AlgoritmoFIFO();
        asc = new AlgoritmoSC();
        amru = new AlgoritmoMRU();


        pAlgo.removeAll();
        pAlgo.add(getAlgo().getPanel());
        validate();
    }

    private void criarAlteracoesAleatorias() {
        for (Pagina p : memoria) {
            if (p != null) {
                p.setModificada(Math.round(Math.random()) == 0);
                p.setReferenciada(Math.round(Math.random()) == 0);
            }
        }
        lMemoria.repaint();
    }
}
